package com.yunhe.transfer.websocket;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yunhe.common.model.base.DataTransferDTO;
import com.yunhe.transfer.service.data.HeartbeatService;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 量测实时数据WebSocket处理类
 * @author liuronglei
 */
public class HeartbeatWSHandler extends TextWebSocketHandler {
    private static final ObjectMapper mapper = new ObjectMapper();
    @Autowired
    private HeartbeatService heartbeatService;
    private List<WebSocketSession> sessionList = new ArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        sessionList.add(session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        sessionList.remove(session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        String payload = message.getPayload();
        try {
            DataTransferDTO dataMap = mapper.readValue(payload, DataTransferDTO.class);
            Long stationCode = dataMap.getStationCode();
            heartbeatService.updateHeartbeatTimeMillis(stationCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 每5秒执行心跳上传
    // 或者取yml配置:custom.collect.heartbeat.frequency
    @SchedulerLock(name = "HeartbeatClientWsTask", lockAtMostFor = "PT3S")
    @Scheduled(cron = "0/5 * * * * ? ")
    public void heartbeatClientWsTask() throws Exception {
        Map<String, Long> sendResult = new HashMap<>();
        sendResult.put("heartbeat", System.currentTimeMillis());
        TextMessage textMessage = new TextMessage(mapper.writeValueAsString(sendResult));
        // 循环所有连接上来的WS连接
        for (WebSocketSession session : sessionList) {
            session.sendMessage(textMessage);
        }
    }
}
